

<template>
    <page ref="pageRef" title="天降红包" nav-color="transparent" light>
        <un v-if="!ongoing" @refresh="refresh"></un>
        <rain v-else :left-second="leftSecond" @lottery="lottery"></rain>
        <view class="index" @click="$router.index()">首页</view>
        <rule ref="ruleRef" />
        <result ref="resultRef" />
    </page>
</template>

<script>
import un from './un.vue'
import rain from './rain.vue'
import rule from './rule'
import result from './result'

export default {
    components: { un, rain, rule, result },
    data() {
        return {
            redData: null,
            ongoing: false,
            leftSecond: 0
        }
    },
    onShow() {
        this.getData()
    },
    onHide() {
        this.stopTimer()
    },
    methods: {
        refresh() {
            this.getData(true)
        },
        async getData(loading = false) {
            const res = await this.$service.weal.redPacketRain(loading)
            if (res) {
                this.ongoing = res.ongoing
                this.leftSecond = res.leftSecond
                if (this.ongoing && this.leftSecond > 0) {
                    this.startTimer()
                } else {
                    this.stopTimer()
                }
            }
        },
        startTimer() {
            this.stopTimer()
            this.timer = setInterval(() => {
                this.leftSecond -= 1
                if (this.leftSecond <= 0) {
                    this.stopTimer()
                    setTimeout(() => {
                        this.getData()
                    }, 0)
                }
            }, 1000)
        },
        stopTimer() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
        },
        showRule() {
            this.$refs.ruleRef.show()
        },
        async lottery() {
            const res = await this.$service.weal.redPacketRainJoin()
            if (res) {
                this.$refs.resultRef.show(res)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.index {
    position: fixed;
    top: 180rpx;
    right: 0;
    width: 96rpx;
    height: 48rpx;
    background: linear-gradient(315deg, #0bd1ce 0%, #3ba1ff 100%);
    border-radius: 200rpx 0px 0px 200rpx;
    line-height: 48rpx;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
    z-index: 100;
}
.rule {
    position: fixed;
    top: 260rpx;
    right: 0;
    width: 96rpx;
    height: 48rpx;
    background: linear-gradient(315deg, #ff345a 0%, #ffa25e 100%);
    border-radius: 200rpx 0px 0px 200rpx;
    line-height: 48rpx;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
    z-index: 100;
}
</style>